<template>
  <div class="app-container calendar-list-container z-h-100">
    <el-row :span="24" class="z-h-100">
      <el-col v-loading="treeData.length===0" :xs="24" :sm="24" :md="5" class="filter-container-tree z-h-100">
        <div class="filter-container">
          <el-button-group>
            <el-button
              v-if="menuManager_btn_add"
              type="primary"
              size="small"
              icon="plus"
              @click="handlerAdd"
            >添加</el-button>
            <el-button
              v-if="menuManager_btn_edit"
              type="primary"
              size="small"
              icon="edit"
              @click="handlerEdit"
            >编辑</el-button>
            <el-button
              v-if="menuManager_btn_del"
              type="primary"
              size="small"
              icon="delete"
              @click="handleDelete"
            >删除</el-button>
          </el-button-group>
        </div>
        <el-scrollbar ref="treeScrollbar" class="scrollbarCls">
          <div class="treeWrapper">
            <el-tree
              :data="treeData"
              :default-expanded-keys="aExpandedKeys"
              :filter-node-method="filterNode"
              :props="defaultProps"
              class="filter-tree"
              node-key="id"
              highlight-current
              :expand-on-click-node="false"
              @node-click="getNodeData"
              @node-expand="toggleChange"
              @node-collapse="toggleChange"
            />
          </div>
        </el-scrollbar>
      </el-col>
      <el-col :xs="24" :sm="24" :md="19" class="authorDept__main z-h-100">
        <el-scrollbar class="scrollbarCls">
          <el-form
            ref="form"
            :label-position="labelPosition"
            :model="form"
            :rules="rules"
            label-width="80px"
            size="mini"
          >
            <el-form-item label="父级节点" prop="parentId">
              <el-input v-model="form.parentId" :disabled="true" placeholder="请输入父级节点" />
            </el-form-item>
            <el-form-item v-if="form.menuId" label="节点ID" prop="menuId">
              <el-input
                v-model="form.menuId"
                :disabled="formEdit || formStatus === 'update'"
                type="number"
                placeholder="请输入节点ID"
              />
            </el-form-item>
            <el-form-item label="标题" prop="name">
              <el-input v-model="form.name" :disabled="formEdit" placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-radio v-model="form.type" :disabled="formEdit" label="0">菜单</el-radio>
              <el-radio v-model="form.type" :disabled="formEdit" label="1">按钮</el-radio>
            </el-form-item>
            <el-form-item v-if="isParentNode" label="系统标识" prop="systemCode">
              <el-input v-model="form.systemCode" :disabled="formEdit" placeholder="请输入系统标识" />
            </el-form-item>
            <el-form-item v-if="form.type === '1'" label="权限标识" prop="permission">
              <el-input v-model="form.permission" :disabled="formEdit" placeholder="请输入权限标识" />
            </el-form-item>
            <el-form-item v-if="form.type === '0'" label="默认项目" prop="needProject">
              <el-radio v-model="form.needProject" :disabled="formEdit" label="1">需要</el-radio>
              <el-radio v-model="form.needProject" :disabled="formEdit" label="0">不需要</el-radio>
            </el-form-item>
            <el-form-item v-if="form.type === '0'" label="打开方式" prop="pageMode">
              <el-radio v-model="form.pageMode" :disabled="formEdit" label="1">内部</el-radio>
              <el-radio v-model="form.pageMode" :disabled="formEdit" label="2">iframe</el-radio>
              <el-radio v-model="form.pageMode" :disabled="formEdit" label="3">新页签</el-radio>
            </el-form-item>
            <el-form-item v-if="form.type === '0'" label="地址">
              <el-input
                v-model="form.path"
                :disabled="formEdit"
                placeholder="/xx/xxx || http://"
              />
            </el-form-item>
            <el-form-item v-if="form.type === '0'" label="图标" prop="icon">
              <Icon :type="choseIconUrl || 'icon-tianjia2'" size="20" @click="choseIconFun" />
            </el-form-item>
            <el-form-item v-if="form.type === '0'" label="排序" prop="sort">
              <el-input
                v-model="form.sort"
                :disabled="formEdit"
                type="number"
                placeholder="请输入排序"
              />
            </el-form-item>
            <el-form-item v-if="form.type === '0'" label="路由缓冲" prop="type">
              <el-switch
                v-model="form.keepAlive"
                :disabled="formEdit"
                :active-value="&quot;0&quot;"
                :inactive-value="&quot;1&quot;"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </el-form-item>
            <el-form-item v-if="formStatus === 'update'">
              <el-button type="primary" @click="update">更新</el-button>
              <el-button @click="onCancel">取消</el-button>
            </el-form-item>
            <el-form-item v-if="formStatus === 'create'">
              <el-button type="primary" @click="create">保存</el-button>
              <el-button @click="onCancel">取消</el-button>
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </el-col>
    </el-row>
    <!-- <basic-container class="z-h-100">
      <div class="filter-container">
        <el-button-group>
          <el-button
            v-if="menuManager_btn_add"
            type="primary"
            size="small"
            icon="plus"
            @click="handlerAdd"
          >添加</el-button>
          <el-button
            v-if="menuManager_btn_edit"
            type="primary"
            size="small"
            icon="edit"
            @click="handlerEdit"
          >编辑</el-button>
          <el-button
            v-if="menuManager_btn_del"
            type="primary"
            size="small"
            icon="delete"
            @click="handleDelete"
          >删除</el-button>
        </el-button-group>
      </div>

      <el-row class="authorMenu-container">
        <el-col :span="8" style="margin-top:15px; padding-right:15px;" class="z-h-100">
          <el-scrollbar ref="treeScrollbar" class="scrollbarCls">
            <el-tree
              :data="treeData"
              :default-expanded-keys="aExpandedKeys"
              :filter-node-method="filterNode"
              :props="defaultProps"
              class="filter-tree"
              node-key="id"
              highlight-current
              :expand-on-click-node="false"
              @node-click="getNodeData"
              @node-expand="toggleChange"
              @node-collapse="toggleChange"
            />
          </el-scrollbar>
        </el-col>
        <el-col :span="16" style="margin-top:15px;">
          <el-card class="box-card">
            <el-form
              ref="form"
              :label-position="labelPosition"
              :model="form"
              :rules="rules"
              label-width="80px"
            >
              <el-form-item label="父级节点" prop="parentId">
                <el-input v-model="form.parentId" :disabled="true" placeholder="请输入父级节点" />
              </el-form-item>
              <el-form-item v-if="form.menuId" label="节点ID" prop="menuId">
                <el-input
                  v-model="form.menuId"
                  :disabled="formEdit || formStatus === 'update'"
                  type="number"
                  placeholder="请输入节点ID"
                />
              </el-form-item>
              <el-form-item label="标题" prop="name">
                <el-input v-model="form.name" :disabled="formEdit" placeholder="请输入标题" />
              </el-form-item>
              <el-form-item label="类型" prop="type">
                <el-radio v-model="form.type" :disabled="formEdit" label="0">菜单</el-radio>
                <el-radio v-model="form.type" :disabled="formEdit" label="1">按钮</el-radio>
              </el-form-item>
              <el-form-item v-if="isParentNode" label="系统标识" prop="systemCode">
                <el-input v-model="form.systemCode" :disabled="formEdit" placeholder="请输入系统标识" />
              </el-form-item>
              <el-form-item v-if="form.type === '1'" label="权限标识" prop="permission">
                <el-input v-model="form.permission" :disabled="formEdit" placeholder="请输入权限标识" />
              </el-form-item>
              <el-form-item v-if="form.type === '0'" label="默认项目" prop="needProject">
                <el-radio v-model="form.needProject" :disabled="formEdit" label="1">需要</el-radio>
                <el-radio v-model="form.needProject" :disabled="formEdit" label="0">不需要</el-radio>
              </el-form-item>
              <el-form-item v-if="form.type === '0'" label="打开方式" prop="pageMode">
                <el-radio v-model="form.pageMode" :disabled="formEdit" label="1">内部</el-radio>
                <el-radio v-model="form.pageMode" :disabled="formEdit" label="2">iframe</el-radio>
                <el-radio v-model="form.pageMode" :disabled="formEdit" label="3">新页签</el-radio>
              </el-form-item>
              <el-form-item v-if="form.type === '0'" label="地址">
                <el-input
                  v-model="form.path"
                  :disabled="formEdit"
                  placeholder="/xx/xxx || http://"
                />
              </el-form-item>
              <el-form-item v-if="form.type === '0'" label="图标" prop="icon">
                <Icon :type="choseIconUrl || 'icon-tianjia2'" size="20" @click="choseIconFun" />
              </el-form-item>
              <el-form-item v-if="form.type === '0'" label="排序" prop="sort">
                <el-input
                  v-model="form.sort"
                  :disabled="formEdit"
                  type="number"
                  placeholder="请输入排序"
                />
              </el-form-item>
              <el-form-item v-if="form.type === '0'" label="路由缓冲" prop="type">
                <el-switch
                  v-model="form.keepAlive"
                  :disabled="formEdit"
                  :active-value="&quot;0&quot;"
                  :inactive-value="&quot;1&quot;"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
              </el-form-item>
              <el-form-item v-if="formStatus === 'update'">
                <el-button type="primary" @click="update">更新</el-button>
                <el-button @click="onCancel">取消</el-button>
              </el-form-item>
              <el-form-item v-if="formStatus === 'create'">
                <el-button type="primary" @click="create">保存</el-button>
                <el-button @click="onCancel">取消</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
      <choseIcon ref="choseIcon" :dialog-visible="dialogVisible" @close="closeIconFun" @defineFun="defineFun" />
    </basic-container> -->
  </div>
</template>

<script>
import { addObj, delObj, fetchMenuTree, getObj, putObj, uploadMenuImg } from '@/api/admin/menu'
import { mapGetters } from 'vuex'
import iconList from '@/const/iconList'
import website from '@/const/website.js'
import choseIcon from './choseIcon'
export default {
  name: 'AuthorMenu',
  filters: {
    typeFilter(type) {
      const typeMap = {
        0: '菜单',
        1: '按钮'
      }
      return typeMap[type]
    }
  },
  components: {
    choseIcon
  },
  data() {
    return {
      iconList: iconList,
      list: null,
      total: null,
      formEdit: true,
      formAdd: true,
      formStatus: '',
      showElement: false,
      typeOptions: ['0', '1'],
      listQuery: {
        name: undefined
      },
      treeData: [],
      oExpandedKey: {
        // key (from tree id) : expandedOrNot boolean
      },
      oTreeNodeChildren: {
        // id1 : [children] (from tree node id1)
        // id2 : [children] (from tree node id2)
      },
      aExpandedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      labelPosition: 'right',
      form: {
        permission: undefined,
        name: undefined,
        menuId: undefined,
        parentId: undefined,
        icon: undefined,
        sort: undefined,
        component: undefined,
        type: undefined,
        needProject: undefined,
        path: undefined,
        color: undefined,
        grey: undefined,
        system_code: ''
      },
      radio: '1',
      currentId: -1,
      menuManager_btn_add: false,
      menuManager_btn_edit: false,
      menuManager_btn_del: false,
      rules: {
        menuId: [{ required: true, message: '节点ID不合法', trigger: 'blur' }],
        name: [{ required: true, message: '标题不合法', trigger: 'blur' }],
        type: [{ required: true, message: '类型不合法', trigger: 'blur' }],
        needProject: [{ required: true, message: '默认项目不合法', trigger: 'blur' }],
        path: [{ validator: this.checkPath, trigger: 'blur' }],
        systemCode: [{ required: true, trigger: 'blur', message: '系统标识必填' }]
      },
      dialogVisible: false, // 是否显示选择图标弹窗
      choseIconUrl: 'icon-tianjia2',
      isParentNode: true // 是否是父节点
    }
  },
  computed: {
    ...mapGetters(['elements', 'permissions'])
  },

  created() {
    console.log('xxx')
    this.getList()
    this.menuManager_btn_add = this.permissions.sys_menu_add
    this.menuManager_btn_edit = this.permissions.sys_menu_edit
    this.menuManager_btn_del = this.permissions.sys_menu_del
  },
  methods: {
    // 树发生变化滚动条变化
    toggleChange() {
      this.$refs.treeScrollbar.update()
    },
    choseIconFun() {
      console.log(this.formEdit)
      console.log(this.formStatus)
      if (!this.formEdit) {
        this.dialogVisible = true
        console.log(this.$refs.choseIcon)
        this.$refs.choseIcon.setIconName(this.choseIconUrl)
      }
    },
    defineFun(item) {
      console.log(item)
      this.dialogVisible = false
      this.choseIconUrl = item.iconName
    },
    closeIconFun() {
      this.dialogVisible = false
    },
    getList() {
      fetchMenuTree(this.listQuery).then(response => {
        this.treeData = response.data.data
      })
    },
    filterNode(value, data) {
      if (!value) {
        return true
      }
      return data.label.indexOf(value) !== -1
    },

    nodeExpand(data) {
      const aChildren = data.children
      if (aChildren.length > 0) {
        this.oExpandedKey[data.id] = true
        this.oTreeNodeChildren[data.id] = aChildren
      }
      this.setExpandedKeys()
    },
    nodeCollapse(data) {
      this.oExpandedKey[data.id] = false
      // 如果有子节点
      this.treeRecursion(this.oTreeNodeChildren[data.id], oNode => {
        this.oExpandedKey[oNode.id] = false
      })
      this.setExpandedKeys()
    },
    setExpandedKeys() {
      const oTemp = this.oExpandedKey
      this.aExpandedKeys = []
      for (const sKey in oTemp) {
        if (oTemp[sKey]) {
          // eslint-disable-next-line radix
          this.aExpandedKeys.push(parseInt(sKey))
        }
      }
    },
    treeRecursion(aChildren, fnCallback) {
      if (aChildren) {
        for (let i = 0; i < aChildren.length; ++i) {
          const oNode = aChildren[i]
          fnCallback && fnCallback(oNode)
          this.treeRecursion(oNode.children, fnCallback)
        }
      }
    },

    getNodeData(data) {
      console.log(data)
      if (!this.formEdit) {
        this.formStatus = 'update'
      }
      getObj(data.id).then(response => {
        this.form = response.data.data
      })
      this.currentId = data.id
      this.showElement = true
      this.choseIconUrl = data.icon
      this.isParentNode = data.parentId === '-1' // 是否是父节点
    },
    checkPath(rule, value, callback) {
      if (this.form.type === '1') {
        callback()
      } else if (this.validatenull(value)) {
        callback(new Error('请输入前端组件'))
      } else {
        callback()
      }
    },
    handlerEdit() {
      if (this.form.menuId) {
        this.formEdit = false
        this.formStatus = 'update'
      }
    },
    handlerAdd() {
      this.resetForm()
      this.formEdit = false
      this.formStatus = 'create'
    },
    handleDelete() {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delObj(this.currentId).then(() => {
          this.getList()
          this.resetForm()
          this.onCancel()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    update() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.icon = this.choseIconUrl
          console.log(this.form)
          putObj(this.form).then(() => {
            this.$store.dispatch('GetMenu')
            this.getList()
            this.formEdit = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    create() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          addObj(this.form).then(() => {
            this.getList()
            this.formEdit = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    onCancel() {
      this.formEdit = true
      this.formStatus = ''
    },
    resetForm() {
      this.form = {
        permission: undefined,
        name: undefined,
        menuId: undefined,
        parentId: this.currentId,
        icon: undefined,
        sort: undefined,
        component: undefined,
        type: undefined,
        needProject: '0',
        path: undefined,
        color: undefined,
        grey: undefined
      }
    },
    // 点击选择图片
    fn_iconClick(ev) {
      if (this.formEdit) {
        return
      }
      this.$refs.iconFile.value = ''
      this.$refs.iconFile.click()
    },
    // 选择图片
    fn_iconChange(ev) {
      const exg = /\.png$/
      const ev_target = ev.target
      const _this = this
      const file = ev_target.files[0]
      const fileName = file.name
      const filePath = ev_target.value

      // 验证是否是png图片
      if (!exg.test(fileName)) {
        this.$message('请上传png格式')
        ev_target.value = ''
        return
      }

      // 验证是否是png的尺寸
      if (filePath) {
        const reader = new FileReader()
        reader.onloadend = function(e) {
          const image = new Image()
          const data = e.target.result
          image.src = data
          if (image.width > website.COLOR_WIDTH || image.height > website.COLOR_HEIGHT) {
            _this.$message(`png图片须等于或小于${website.COLOR_WIDTH}X${website.COLOR_HEIGHT}`)
            ev_target.value = ''
            return
          }

          // 通过校验，则上传图片
          _this.fn_uploadMenuImg(file)
        }
        reader.readAsDataURL(file)
      }
    },
    // 上传图片
    fn_uploadMenuImg(file) {
      uploadMenuImg({
        file,
        colorW: website.COLOR_WIDTH,
        colorH: website.COLOR_HEIGHT,
        greyH: website.GREY_HEIGHT,
        greyW: website.GREY_WIDTH
      }).then(res => {
        if (res.data.code === 0) {
          this.form.icon = res.data.data.colorUrl
          this.form.color = res.data.data.color
          this.form.grey = res.data.data.grey
        } else {
          this.$message({
            type: 'error',
            message: '上传图片失败'
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.app-container{
  background-color:#fff;
}
.filter-container-tree{
  padding:10px;
  .filter-container{
    margin-bottom: 10px;
  }
  .treeWrapper{
      height:calc(100% - 45px);
    }
}
.authorDept__main{
  padding: 10px;
}
// .basic-container{
//   /deep/ .el-card {
//     height: 100%;
//     .el-card__body{
//       height: 100%;
//       .authorMenu-container{
//         height: calc(100% - 32px);
//       }
//     }
//   }
// }
/deep/ .menu_icon {
  height: 40px;
  display: flex;
  align-items: center;
  // 上传图标的提示
  .icon_tip {
    display: inline-block;
    margin-left: 10px;
    color: #c0c4cc;
  }
  img {
    height: 40px;
    width: 40px;
  }
  .el-radio {
    margin-right: 0px;
    margin-left: 30px;
  }
  .iconFile {
    display: none;
  }
}
</style>

